<template>
    <view class="wrap">
        <view class="top"></view>
        <view class="content">
            <view class="title">欢迎登录uview商城模板</view>
            <u-form ref="validateFormRef" :model="validateForm.value">
                <u-form-item label="账号" prop="username" :border-bottom="false">
                    <u-input class="u-border-bottom" v-model="validateForm.value.username" placeholder="请输入账号"/>
                </u-form-item>
                <u-form-item label="密码" prop="password" :border-bottom="false">
                    <u-input type="password" class="u-border-bottom" v-model="validateForm.value.password" placeholder="请输入密码"/>
                </u-form-item>
            </u-form>
            <button @tap="submit" :style="[inputStyle]" class="loginBtn">登录</button>
            <view class="alternative">
                <view class="password" @click="navigateTo(`/pages/main/login/register/index`)">注册</view>
                <view class="issue" @click="navigateTo(`/pages/main/login/forget-password/index`)">忘记密码</view>
            </view>
        </view>
        <view class="buttom">
            <div style="display: flex;">
                <div style="width: 100%"></div>
                <div style="padding: 66px;">
                    <div @click="wechatLogin()">
                        <view class="icon">
                            <u-icon size="70" name="weixin-fill" color="rgb(83,194,64)"></u-icon>
                        </view>
                        微信
                    </div>
                </div>
                <div style="width: 100%"></div>
            </div>
            <!--<view class="loginType">-->
            <!--<view class="wechat item">-->
            <!--<view class="icon">-->
            <!--<u-icon size="70" name="weixin-fill" color="rgb(83,194,64)"></u-icon>-->
            <!--</view>-->
            <!--微信-->
            <!--</view>-->
            <!--<view class="QQ item">-->
            <!--<view class="icon">-->
            <!--<u-icon size="70" name="qq-fill" color="rgb(17,183,233)"></u-icon>-->
            <!--</view>-->
            <!--QQ-->
            <!--</view>-->
            <!--</view>-->
            <view class="hint" style="position: absolute; bottom: 0px;">
                <div style="margin-top: 10px; margin-bottom: 10px;">
                    <official-account style="width: 100%;"></official-account>
                </div>

                登录代表同意
                <text class="link" @click="navigateTo(`/pages/common/agreement/index`)">uview商城模板用户协议、隐私政策，</text>
                并授权使用您的uview商城模板账号信息（如昵称、头像、收获地址）以便您统一管理
            </view>
        </view>
    </view>
</template>

<script>
    import {LoginService} from "../../../dev/services/login.service";
    import {LocalStorageUtil} from "../../../dev/core/utils/local-storage.util";
    import {CommonUtil} from "../../../dev/core/utils/common.util";
    import {SysUserThirdLoginService} from "../../../dev/services/sys_user_third_login.service";
    import {initPayEnvironment} from "../../../dev/core/utils/pay";

    export default {
        data() {
            return {
                show: false,
                validateForm: {
                    value: {
                        username: '',
                        password: ''
                    },
                    rules: {
                        username: [
                            {required: true, message: '请输入账号!', trigger: 'blur'},
                            {pattern: /^(?=.*\S).+$/, message: '请输入账号!', trigger: 'blur'},
                            {
                                trigger: ['change', 'blur'],
                                asyncValidator: (rule, value, callback) => {
                                    if (!value) {
                                        LocalStorageUtil.removeItem("login");
                                    }
                                    callback();
                                }
                            }
                        ],
                        password: [
                            {required: true, message: '请输入密码!', trigger: 'blur'},
                            {pattern: /^(?=.*\S).+$/, message: '请输入密码!', trigger: 'blur'}
                        ]
                    }
                }
            }
        },
        computed: {
            inputStyle() {
                let style = {};
                if (this.validateForm.value.username) {
                    style.color = "#fff";
                    style.backgroundColor = this.$u.color['warning'];
                }
                return style;
            }
        },
        onShow() {
            // 检查本地是否有缓存数据
            let _self = this;
            if (_self.urlParams.isScan === "1") {  // 是否扫码登陆
                console.log("通过扫码进入登录页面", _self.urlParams);
                initPayEnvironment().then(result => {
                    let object = Object.assign({}, _self.urlParams);
                    object.loginId = _self.globalVariable.userInfo.unionid;
                    object.loginType = "0";  // 类型：0-微信小程序，1-微信APP
                    new LoginService().loginByScan(object).then(result => {
                        _self.loginResultHandle(result);
                    })
                });
            } else if (_self.urlParams.isFwh === "1") {  // 是否从服务号进入
                console.log("通过从服务号进入登录页面", _self.urlParams);
                initPayEnvironment().then(result => {
                    let object = Object.assign({}, _self.urlParams);
                    object.loginId = _self.globalVariable.userInfo.unionid;
                    object.loginType = "0";  // 类型：0-微信小程序，1-微信APP
                    new LoginService().loginByFwh(object).then(result => {
                        _self.loginResultHandle(result);
                    })
                });
            } else {  // 默认打开小程序
                console.log("普通方式进入登录页面", _self.urlParams);
                /* let token = LocalStorageUtil.getItem("token");
                 let userInfo = LocalStorageUtil.getItem("userInfo");
                 _self.globalVariable.orderSequenceNumber = null;  // 删除已扫码的餐饮号
                 if (token && userInfo) {
                     _self.globalVariable.token = token;
                     _self.globalVariable.userInfo = userInfo;
                     // if (this.$route.path === "/" || this.$route.path === "") {
                     //     uni.reLaunch({
                     //         url: '/pages/sub/sub1-tabs/tabs/index',
                     //     });
                     // }
                     uni.reLaunch({
                         url: '/pages/sub/sub1-tabs/tabs/index',
                     });
                 }*/

                let login = LocalStorageUtil.getItem("login");
                if (login) {
                    _self.validateForm.value.username = login.username;
                }
            }
        },
        methods: {
            submit() {
                const _self = this;
                this.$refs.validateFormRef.validate(valid => {
                    if (valid) {
                        console.log('验证通过', _self.validateForm.value);
                        new LoginService().login({
                            username: _self.validateForm.value.username,
                            password: _self.validateForm.value.password,
                        }).then(result => {
                            LocalStorageUtil.setItem("login", _self.validateForm.value);
                            _self.loginResultHandle(result);
                        })
                    } else {
                        console.log('验证失败');
                    }
                });
            },
            wechatLogin() {
                const _self = this;
                new SysUserThirdLoginService().weixinLoginByUnionid().then(result => {
                    _self.loginResultHandle(result);
                });
            },
            loginResultHandle(result) {
                const _self = this;
                if (result.status === 'success') {
                    _self.globalVariable.token = result.token;
                    _self.globalVariable.userInfo = result.userInfo;
                    _self.globalVariable.userInfo.unionid = result.unionid;
                    _self.globalVariable.orderSequenceNumber = result.orderSequenceNumber;  // 餐饮号，可能扫码时附带。

                    // 如果是审核账号，则屏蔽首页定制
                    if (_self.globalVariable.userInfo.username === "tgh004005") {
                        delete _self.globalVariable.userInfo.tbCommunity.tbCommunityHomeConfig;
                    }

                    if (_self.globalVariable.userInfo.tbCommunityUser.enabledLogin) {
                        LocalStorageUtil.setItem("token", _self.globalVariable.token);
                        LocalStorageUtil.setItem("userInfo", _self.globalVariable.userInfo);
                        CommonUtil.toastReLaunch("登录成功，正在跳转到首页", '/pages/sub/sub1-tabs/tabs/index');
                    } else {
                        CommonUtil.toast(`该账号禁止登录【${_self.globalVariable.userInfo.tbCommunityUser.tbCommunity.name}】请联系商城管理员。`, 5000);
                    }
                } else {
                    if (result.message) {
                        CommonUtil.toast(result.message, 3000);
                    }
                }
            }
        }
    };
</script>

<style lang="scss" scoped>
    @import "./index.scss";
</style>
